package com.wolfalpha.lwtool.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.ParseException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.wolfalpha.lwtool.constant.Application;
import com.wolfalpha.lwtool.constant.Constant;
import com.wolfalpha.lwtool.constant.StringUtils;
import com.wolfalpha.lwtool.db.DBDao;
import com.wolfalpha.lwtool.exception.InternetErrorException;
import com.wolfalpha.lwtool.map.MapsAndLists;
import com.wolfalpha.lwtool.service.BaseService;
import com.wolfalpha.lwtool.service.UserService;
import com.wolfalpha.lwtool.service.ZQService;
import com.wolfalpha.lwtool.vo.DB;
import com.wolfalpha.lwtool.vo.FFCity;
import com.wolfalpha.lwtool.vo.FFJobInfo;
import com.wolfalpha.lwtool.vo.FFListJob;
import com.wolfalpha.lwtool.vo.JobTemp;

public class BaseServiceImpl implements BaseService {
	@SuppressLint("SimpleDateFormat")
	public static SimpleDateFormat yfr = new SimpleDateFormat("yyyy-MM-dd");
	@SuppressLint("SimpleDateFormat")
	public static SimpleDateFormat yfr1 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private List<Integer> js = new ArrayList<Integer>();
	private DBDao dao = null;
	private List<DB> dbs;
	private Context context;
	private ZQService zqSrv;
	private UserService saveService;
	private boolean inzq = false;
	private boolean lock = false;
	private String time;
	private int frequ = 1;// 频率
	private int count = 0;
	private Timer timerStatic;
	private Thread dyThread;
	protected Timer timerDy;

	public BaseServiceImpl(Context context) {
		this.context = context;
		zqSrv = new ZQServiceImpl();
		saveService = new UserServiceImpl();
		dao = Application.getDao(context);
		init();
	}

	public String getNowTime() {
		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		return yfr1.format(date);
	}

	/**
	 * 初始化环境变量
	 */
	public void init() {
		lock = false;
		dbs = dao.query();
		js.clear();
		MapsAndLists.getJts().clear();
		for (DB db : dbs) {
			js.add(db.getId());
		}

		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		// time = "2015-04-08";
		time = yfr.format(date);

		Log.i("time=", time);

		SharedPreferences shp = PreferenceManager
				.getDefaultSharedPreferences(context);
		frequ = shp.getInt("frequency", 0) + 1;
		if (frequ >= 7) {
			frequ = 60;
		}
	}

	/**
	 * 中断线程
	 */
	@Override
	public void stopWork(boolean stop) {
		if (stop) {
			if (timerStatic != null) {
				timerStatic.cancel();
			}
			if (timerDy != null) {
				timerDy.cancel();
			}
			if (dyThread != null) {
				// dyThread.destroy();
				dyThread = null;
			}
			inzq = false;
		}
	}

	/**
	 * 静态抓取 刷新频率
	 */
	@Override
	public void stayZQ() {
		if (inzq)
			return;
		inzq = true;
		sendMsg(Application.N_MAIN, "抓取开始");
		timerStatic = new Timer();
		MyTask mt = new MyTask();
		timerStatic.schedule(mt, 1000, frequ * 60000);// 根据设置
	}

	/**
	 * 动态抓取 点击一次抓取一次
	 */
	@Override
	public void dynamicZQ() {
		if (inzq) {
			return;
		}

		new Thread(new Runnable() {

			@Override
			public void run() {

				sendMsg(Application.N_DYNAMIC, "开始抓取");
				for (FFCity fcty : Constant.citys) {
					while (inzq)
						;
					sendMsg(Application.N_DYNAMIC, "当前城市:" + fcty.getCity());
					inzq = true;
					init();
					// 第一步:获取所有&存入本地
					if (!lock) {
						try {
							getListOfJobs(fcty);
						} catch (Exception e) {
							e.printStackTrace();
							continue;
						}
					}
					if (!lock) {
						// 第二步:获取单个&存入远程
						MyTimerTask mt = new MyTimerTask();
						timerDy = new Timer();
						timerDy.schedule(mt, 100, 1000);
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 监听刷新
	 * 
	 * @throws Exception
	 */
	public boolean getRefreshJobs(FFCity fct) {

		System.out.println("Now time:" + getNowTime());

		init();
		count++;
		String str0 = "第" + count + "次刷新|";
		if (js.size() == 0)
			js.add(7278);// 设置默认
		System.out.println("js=" + js);
		System.out.println("MapJobs" + MapsAndLists.getJts().toString());
		List<FFListJob> jobs = new ArrayList<FFListJob>();

		if (MapsAndLists.getJts().size() == 0) {
			try {
				jobs = zqSrv.getRefreshJobs(Constant.listUrl,
						Constant.getRefreshMap(js.get(js.size() - 1), fct));
			} catch (InternetErrorException e) {
				sendMsg(Application.N_MAIN, str0 + "网络错误！");
				e.printStackTrace();
			}
			System.out.println("refresh1id = " + js.get(js.size() - 1));
		} else {
			int x = MapsAndLists.getJts().get(MapsAndLists.getJts().size() - 1)
					.getFbinfo().getId();
			try {
				jobs = zqSrv.getRefreshJobs(Constant.listUrl,
						Constant.getRefreshMap(x, fct));
			} catch (InternetErrorException e) {
				sendMsg(Application.N_MAIN, str0 + "网络错误！");
				e.printStackTrace();
			}
			System.out.println("refresh2id = " + x);
		}
		if (jobs == null) {
			sendMsg(Application.N_MAIN, str0 + "没有更新");
			return false;
		}

		for (FFListJob jb : jobs) {
			// Log.i("job:",jb.toString());

			DB db = new DB();
			db.setId(jb.getId());
			db.setTime(String.valueOf(jb.getPublishDate()));
			db.setTitle(String.valueOf(jb.getJobTitle()));
			db.setMdate(getNowTime());
			if (String.valueOf(jb.getPublishDate()).contains(time)) {
				String str = str0 + "该记录已经过期[id=" + db.getId() + "]";
				System.out.println(str);
				if (!js.contains(db.getId()))
					dao.addSingleDB(db);
				sendMsg(Application.N_MAIN, str);
				continue;
			} else if (js == null || !js.contains(db.getId())) {
				MapsAndLists.addJts(jb, fct);
				dao.addSingleDB(db);
				System.out.println("Added Success!");
				String str = str0 + "增加并写入本地[id=" + db.getId() + "]";
				System.out.println(str);
				sendMsg(Application.N_MAIN, str);
			} else {
				System.out.println("Already exist!");
				String str = str0 + "该记录已存在本地[id=" + db.getId() + "]";
				System.out.println(str);
				sendMsg(Application.N_MAIN, str);
			}
		}
		if (MapsAndLists.getJts().size() == 0) {
			System.out.println("无");
			return false;
		}
		return true;

	}

	/**
	 * 正常抓取
	 * 
	 * @throws Exception
	 */
	public void getListOfJobs(FFCity fct) {
		lock = true;
		List<FFListJob> jobs = new ArrayList<FFListJob>();
		try {
			jobs = zqSrv.getJobs(Constant.listUrl, Constant.getHeadMap(fct));
			Log.i("jobs", String.valueOf(jobs.size()));
		} catch (InternetErrorException e1) {
			sendMsg(Application.N_FRONT, "网络错误！");
			e1.printStackTrace();
		}
		if (jobs.size() == 0) {
			lock = false;
			return;
		}
		sendMsg(Application.N_DYNAMIC, "抓取1次");
		// 收集更多的
		// 循环5次
		for (int i = 0; i < 5; i++) {
			sendMsg(Application.N_DYNAMIC, "抓取" + (i + 2) + "次");
			List<FFListJob> mjbs = new ArrayList<FFListJob>();
			try {
				mjbs = zqSrv.getMoreJobs(Constant.listUrl, Constant.getMoreMap(
						jobs.get(jobs.size() - 1).getId(), fct));
			} catch (InternetErrorException e) {
				sendMsg(Application.N_FRONT, "网络错误！");
				e.printStackTrace();
			}
			if (mjbs != null) {
				for (FFListJob _jb : mjbs) {
					jobs.add(_jb);
				}
			} else {
				System.out.println("循环" + i + "没有更多");
			}
		}
		for (FFListJob jb : jobs) {
			// Log.i("job:",jb.toString());
			DB db = new DB();
			db.setId(jb.getId());
			db.setTime(String.valueOf(jb.getPublishDate()));
			db.setTitle(String.valueOf(jb.getJobTitle()));
			db.setMdate(getNowTime());
			Log.i("jb.getPublishDate()", String.valueOf(jb.getPublishDate()));
			if (String.valueOf(jb.getPublishDate()).contains(time)) {
				String str = "该记录已经过期[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
				continue;
			} else if (js == null || !js.contains(db.getId())) {
				MapsAndLists.addJts(jb, fct);
				dao.addSingleDB(db);
				System.out.println("Added Success!");
				String str = "增加并写入本地[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
			} else {
				System.out.println("Already exist!");
				String str = "该记录存在本地[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
			}
		}
		lock = false;
	}

	/**
	 * 不断抓取
	 * 
	 * @author ttStudio
	 * 
	 */
	public class MyTask extends TimerTask {
		@Override
		public void run() {
			try {
				for (FFCity fcty : Constant.citys) {
					boolean b = getRefreshJobs(fcty);
					if (b) {
						System.out.println("MapJobs2"
								+ MapsAndLists.getJts().toString());
						MyTimerTask mt = new MyTimerTask();
						if (timerDy == null)
							timerDy = new Timer();
						timerDy.schedule(mt, 100, 200);
						Thread.sleep(1000);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 存入数据
	 * 
	 * @author ttStudio
	 * 
	 */
	public class MyTimerTask extends TimerTask {
		int count = 0;
		private int max = MapsAndLists.getJts().size();

		@Override
		public void run() {
			lock = true;
			try {
				if (count >= max) {
					sendMsg(Application.N_FRONT,
							"FINISH！记录数量：" + String.valueOf(max));
					MapsAndLists.getJts().clear();
					inzq = false;
					lock = false;
					this.cancel();
					return;
				}
				System.out.println("JScount = " + MapsAndLists.getJts().size());
				System.out.println("count = " + count);
				JobTemp jt = MapsAndLists.getJts().get(count);
				FFListJob ljob = jt.getFbinfo();
				FFJobInfo info = zqSrv.getInfo(Constant.infoUrl,
						Constant.getInfoMap(String.valueOf(ljob.getId())));
				MapsAndLists.addJobInfo(info);
				sendMsg(Application.N_FRONT, "解析到第：" + count);
				String str = (String) info.getJobTitle();
				sendMsg(Application.N_FRONT, "开始存入远程一条记录" + count + ":\n["
						+ str + "]");
				try {
					publishJob(info, jt.getFc().getId());
				} catch (Exception e) {
					e.printStackTrace();
				}
				sendMsg(Application.N_FRONT, "GET");

				count++;
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (InternetErrorException e) {
				sendMsg(Application.N_FRONT, "网络错误！");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送广播
	 * 
	 * @param Object
	 */
	private void sendMsg(String activity, Object obj) {
		Intent mIntent = new Intent(activity);
		mIntent.putExtra("msg", String.valueOf(obj));
		// 发送广播
		context.sendBroadcast(mIntent);
	}

	/**
	 * 发布
	 * 
	 * @param jinfo
	 */
	public void publishJob(final FFJobInfo jinfo, final int id) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					saveService.publishJob(String.valueOf(jinfo.getJobTitle()),
							StringUtils.type2Int(String.valueOf(jinfo
									.getJobType())), String.valueOf(jinfo
									.getLinkMan()), StringUtils
									.mobile2Long(String.valueOf(jinfo
											.getTelephone())), id, String
									.valueOf(jinfo.getWorkAddress()),
							StringUtils.peroid2Int(String.valueOf(jinfo
									.getJobNature())),
							StringUtils.getSalary(String.valueOf(jinfo
									.getSalary())), StringUtils.wage2Int(String
									.valueOf(jinfo.getSalary())), StringUtils
									.wage2Int(String.valueOf(jinfo
											.getPaymentMeans())), StringUtils
									.time2Int(String.valueOf(jinfo
											.getWorkTime())), String
									.valueOf(jinfo.getWholeWorkDate()), jinfo
									.getNeedCount(), String.valueOf(jinfo
									.getJobTitle()), String.valueOf(jinfo
									.getDetailMsg()));
				} catch (Exception e) {
					sendMsg(Application.N_FRONT, "网络错误！");
					e.printStackTrace();
				}
			}
		}).start();

	}

	/**
	 * 获取json数据
	 * 
	 * @throws Exception
	 * 
	 */
	@Override
	public String getJsonById(String id) {
		try {
			return zqSrv.postData(Constant.infoUrl, Constant.getInfoMap(id));
		} catch (InternetErrorException e) {
			e.printStackTrace();
		}
		return "";
	}

}
